﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;

namespace Sharp.WebBooter
{
    /// <summary>
    /// 权限过滤器
    /// </summary>
    public class AuthorizationFilter : IActionFilter
    {
        public void OnActionExecuting(HttpRequestMessage requestMessage)
        {
            if (HttpContext.Current == null || HttpContext.Current.User == null)
            {
                return;
            }
            var claimIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;
            if (!claimIdentity.IsAuthenticated) { return; }

            var accessToken = claimIdentity.FindFirstValue("AccessToken");

            requestMessage.Headers.Add("appid", "platformSharp");

            var authValue = new AuthenticationHeaderValue("Bearer", accessToken);
            requestMessage.Headers.Authorization = authValue;
        }

        public Task OnActionExecuted(HttpResponseMessage responseMessage)
        {
            return Task.FromResult(true);
        }

    }
}